import React, { Component } from 'react';
import { Image, View, Text, StyleSheet, FlatList, Platform } from 'react-native';
import * as api from '@/api'

const RenderLoadingView = props => {
    return <View style={styles.container}>
        <Text>Loading Movies...</Text>
    </View>
}

const RenderItem = props => {
    const {item} = props
    return <View style={styles.container}>
        <Image
        source={{ uri: item.posters.thumbnail }}
        style={styles.thumbnail}
        />
        <View style={styles.rightContainer}>
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.year}>{item.year}</Text>
        </View>
    </View>
}

class Movie extends Component {
    constructor(props){
        super(props);
        this.state = {
            data: [],
            loaded: true
        }
    }

    init = () => {
        api.getMovieList().then(resp=>{
            console.log(resp)
            this.setState({
                data: resp.data.movies,
                loaded: false
            })
        })
    }

    componentDidMount(){
        this.init()
    }

    render(){
        const {loaded, data} = this.state
        if(loaded){
            return <RenderLoadingView />
        }
        return (
            <FlatList 
                data={data} 
                keyExtractor={item => item.id} 
                style={styles.list} 
                renderItem={({item}) => <RenderItem item={item}/>}
            />
        )
    }
}

export default Movie;

var styles = StyleSheet.create({
    container: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "center",
      ...Platform.select({
        ios:{
            backgroundColor: "#ccc",
        },
        android:{
            backgroundColor: "#F5FCFF",
        }
      })
      
    },
    rightContainer: {
      flex: 1
    },
    title: {
      fontSize: 20,
      marginBottom: 8,
      textAlign: "center"
    },
    year: {
      textAlign: "center"
    },
    thumbnail: {
      width: 53,
      height: 81
    },
    list: {
      paddingTop: 20,
      backgroundColor: "#F5FCFF"
    }
});